package com.gaowl.yygh.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.gaowl.yygh.sms.service.SmsService;
import com.gaowl.yygh.vo.msm.MsmVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class SmsServiceImpl implements SmsService {

    /*
    * @description: 整合 云通讯短信服务（FW 阿里云）发送验证码
    * @param phone: 待发送验证码的目标手机号
    * @param code:  验证码
    * */
    @Override
    public boolean send(String phone, String code) {
        //判断手机号是否为空
        if(StringUtils.isEmpty(phone)) {
            return false;
        }

        String serverIp = "app.cloopen.com";  //生产环境请求地址
        String serverPort = "8883"; //请求端口
        String accountSId = "8a216da878005a800178a5d088f23b0b";   // 开发者主账号ACCOUNT SID和
        String accountToken = "ac00c65d5c2c4a98a2d4476855ccc159"; // 主账号令牌AUTH TOKEN
        String appId = "8a216da878005a800178a5d08a383b12";  // 应用的appId

        String to = "18362387319";  // 手机号
        String templateId= "1";    // 模板编号
        String[] dataList = {code,"2"};  // 前者为验证码，后者为有效时间

        // 初始化SDK
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);


        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,dataList);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
            return true;
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            return false;
        }
    }


    /*
     * @description: 发送短信
     * @param msmVo: 短信实体类
     * */
    @Override
    public boolean send(MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())) {  // 手机号非空
            String code = (String)msmVo.getParam().get("code");  //
            return this.send(msmVo.getPhone(), code);
        }
        return false;
    }
}
